

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/model/product_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

class SettingChooseDevice extends StatefulWidget {
  const SettingChooseDevice({Key? key}) : super(key: key);

  @override
  State<SettingChooseDevice> createState() => _SettingChooseDeviceState();
}

class _SettingChooseDeviceState extends State<SettingChooseDevice> {

  List<ProductModel> _productList = [];
  int currentPage = 0;

  var searchTextController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();

  bool isAllCheck = false;

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(LocaleKeys.set_up_choose_device.trc(),),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () {
              Get.toNamed(LCRouter.setting_collect_device);
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(10, 10, 15, 10),
              child: Image.asset(IconNames.tep_ref, width: 25,),
            ),
          ),
        ],
      ),
      body: Container(
        width: MainCommon.screenWidth,
        // color: Colors.white,
        child: Column(
          children: [
            // 搜索设备
            Container(
              height: 44 + 10,
              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
              padding: EdgeInsets.fromLTRB(20, 0, 20, 10),
              // margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: Container(
                decoration: BoxDecoration(
                  color: isDarkMode ? Colors.black : Color(0xFFF7F7F7),
                  borderRadius: const BorderRadius.all(
                    Radius.circular(70.0),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(
                      left: 20, right: 20, top: 0, bottom: 0),
                  child: TextField(
                    onChanged: (String txt) {
                      // 搜索数据
                    },
                    style: TextStyle(
                      fontSize: 15,
                      color: Colors.black54,
                    ),
                    textInputAction: TextInputAction.search,
                    controller: searchTextController,
                    cursorColor: Colors.grey, // HexColor('#54D3C2'),  // 光標顏色
                    onEditingComplete: () {
                      _searchFocusNode.unfocus();
                      // 搜索数据
                      _getNewList();
                    },
                    focusNode: _searchFocusNode,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: LocaleKeys.set_up_bianhao_tip.trc(),

                      contentPadding: EdgeInsets.all(0),
                      prefixIcon: Icon(Icons.search,color: Colors.grey,),
                      alignLabelWithHint: true,


                      hintStyle:TextStyle(
                        height: 2.2,
                        color: Colors.grey, //isDarkMode ? Colors.grey : grey,
                      ),
                    ),
                  ),
                ),
              ),
            ),

            Container(height: 20, color: isDarkMode ? Colors.black : Color(0xFFF1F3F8),),
            // 设备列表
            Expanded(
              child: EasyRefresh.custom(
                  header: MaterialHeader(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  footer: MaterialFooter(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  firstRefresh: true,
                  emptyWidget: _productList.isEmpty ? Center(
                    child: Column(
                      children: [
                        SizedBox(height: 50,),
                        Image.asset(IconNames.home_w06, width: MainCommon.screenWidth * 0.6,),
                        Text(LocaleKeys.other_no_data.trc(), style: TextStyle(color: Colors.grey),),
                      ],
                    ),
                  ) : null,
                  slivers: [
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index) {

                                final productModel = _productList[index];

                                // 温度过高
                                bool isNotNormal = productModel.highTemperature.isNotEmpty || productModel.lowerTemperature.isNotEmpty ||
                                                   productModel.t1Failure.isNotEmpty || productModel.t2Failure.isNotEmpty || productModel.t3Failure.isNotEmpty ||
                                                   productModel.condenserClean.isNotEmpty || productModel.doorOpen.isNotEmpty;

                                bool isMoreHigh = productModel.highTemperature.isNotEmpty;  // false; //

                            return Container(
                              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                              child: Column(
                                children: [
                                  Container(
                                    padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                                    child: Row(
                                      children: [
                                        // Icon(productModel.isSelected ? Icons.radio_button_unchecked : Icons.radio_button_checked),
                                        Container(
                                          width: 20,
                                          child: Checkbox(
                                            value: productModel.isSelected,
                                            activeColor: Colors.blue,
                                            shape: CircleBorder(),
                                            onChanged: (bool? value) {
                                              setState(() {
                                                var srcModel = productModel;
                                                srcModel.isSelected = !productModel.isSelected;
                                                final index = _productList.indexOf(productModel);
                                                _productList.replaceRange(index, index + 1, [srcModel]);
                                              });

                                              // 判断是否全为true/false
                                              final tempTrueList = _productList.where((element) => element.isSelected == true).toList();
                                              final tempFalseList = _productList.where((element) => element.isSelected == false).toList();
                                              isAllCheck = tempTrueList.length == _productList.length ? true : isAllCheck;
                                              isAllCheck = tempFalseList.length == _productList.length ? false : isAllCheck;
                                              //
                                              // widget.selectValue([model]);
                                            },
                                          ),
                                        ),


                                        // 冰柜背景
                                        Stack(
                                          alignment: Alignment.center,
                                          children: [
                                            Image.asset(IconNames.home_xzbg, width: 70,),
                                            Positioned(
                                                child: Container(
                                                  width: 70,
                                                  child: CachedNetworkImage(
                                                    fit: BoxFit.fitWidth,
                                                    placeholder: (ctx, url) => Image.asset(IconNames.home_sb_a, fit: BoxFit.fill, width: 70),
                                                    imageUrl: productModel.icon,
                                                    errorWidget: (ctx, url, _) => Image.asset(IconNames.home_sb_a, fit: BoxFit.fill, width: 70 ),
                                                  ),
                                                  // Image.asset(IconNames.home_sb_a, width: 70,),
                                                )
                                            )

                                          ],
                                        ),

                                        SizedBox(width: 5,),
                                        // 第二列
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Container(
                                                child: Text("${productModel.code} ${productModel.modelName} ${productModel.name}", style: TextStyle(fontWeight: FontWeight.bold),),
                                              constraints: BoxConstraints(
                                                maxWidth: 230,
                                              ),
                                            ),

                                            Container(
                                              width: MainCommon.screenWidth - 130,
                                              child: Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Row(
                                                    children: [
                                                      CircleAvatar(
                                                        backgroundColor: productModel.networkStatus == 1 ? Colors.green : Colors.grey,
                                                        radius: 4,
                                                      ),
                                                      SizedBox(width: 5,),
                                                      Text("T1: ${productModel.temperatureOne}℃", style: TextStyle(color: Colors.grey),)
                                                    ],
                                                  ),

                                                  Container(
                                                    decoration: BoxDecoration(
                                                      color: productModel.networkStatus == 1 ? (isNotNormal ? Colors.red.shade50 : Colors.green.shade50) : Colors.grey.shade200,
                                                      borderRadius: BorderRadius.circular(5),
                                                    ),
                                                    padding: EdgeInsets.fromLTRB(5, 2, 5, 3),
                                                    constraints: BoxConstraints(
                                                      maxWidth: productModel.networkStatus == 1 ? (isNotNormal ? MainCommon.screenWidth * 0.3 : double.infinity) : double.infinity,
                                                    ),
                                                    alignment: Alignment.center,
                                                    child: Text("${productModel.warningMessage}",
                                                      style: TextStyle(color: productModel.networkStatus == 1 ? (isNotNormal ? Colors.red : Colors.green) : Colors.grey, fontSize: 12,), maxLines: 1, overflow: TextOverflow.ellipsis,),
                                                  ),

                                                ],
                                              ),
                                            ),

                                            // 地点
                                            Row(
                                              crossAxisAlignment: CrossAxisAlignment.end,
                                              children: [
                                                Image.asset(IconNames.home_positioning, height: 20,),
                                                Text("${productModel.hallName} ${productModel.floorName}", style: TextStyle(color: Colors.grey),),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),

                                  Divider(
                                    height: 1,
                                    thickness: 0,
                                    indent: 0,
                                    endIndent: 0,
                                    // color: Color(0xFFD9D9D9),
                                  ),
                                ],
                              ),
                            );
                          },
                        childCount: _productList.length
                      ),
                    ),
                  ],
                onRefresh: () async {
                    _getNewList();
                },
                onLoad: () async {
                    _getMoreList();
                },
              ),
            ),

            // Container(height: 10, color: isDarkMode ? MainCommon.darkBlueMaterialColor : Color(0xFFF1F3F8),),
            // 加入收藏/批量控制
            Container(
              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white, //Colors.white,
              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 20,
                        child: Checkbox(
                          value: isAllCheck,
                          activeColor: Colors.blue,
                          shape: CircleBorder(side: BorderSide(color: Colors.red, width: 1)),
                          onChanged: (bool? value) {
                            setState(() {
                              isAllCheck = !isAllCheck;

                              // 全选
                              _productList = _productList.map((e) {
                                var srcModel = e;
                                srcModel.isSelected = isAllCheck;
                                return srcModel;
                              }).toList();
                            });


                          },
                        ),
                      ),
                      Text(LocaleKeys.set_up_all.trc(), style: TextStyle(color: Colors.grey),),
                    ],
                  ),

                  Row(
                    children: [
                      InkWell(
                        onTap: () {
                          _productList.forEach((element) {
                            if(element.isSelected) {
                              _addCollect(element.id);
                            }
                          });

                        },
                        child: Container(
                          height: 44,
                          width: MainCommon.screenWidth * 0.3,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(22),
                              border: Border.all(color: Color(0xFF234485))
                          ),
                          alignment: Alignment.center,
                          child: Text(LocaleKeys.set_up_add_collect.trc(), style: TextStyle(color: Color(0xFF234485), fontSize: 16,), textAlign: TextAlign.center,),
                        ),
                      ),
                      SizedBox(width: 10,),
                      InkWell(
                        onTap: (){

                          List<String> _productIdList = [];
                          _productList.forEach((element) {
                            if(element.isSelected) {
                              _productIdList.add(element.id);
                            }
                          });

                          if(_productIdList.isNotEmpty){
                            Get.toNamed(LCRouter.device_setting, arguments: _productIdList);
                          }
                        },
                        child: Container(
                          height: 44,
                          width: MainCommon.screenWidth * 0.3,
                          decoration: BoxDecoration(
                            color: Color(0xFF234485),
                            borderRadius: BorderRadius.circular(22),
                          ),
                          alignment: Alignment.center,
                          // padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
                          child: Text(LocaleKeys.set_up_control_select.trc(), style: TextStyle(color: Colors.white, fontSize: 16), textAlign: TextAlign.center,),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

          ],
        ),
      ),
    );
  }

  _getNewList() {
    _productList = [];
    currentPage = 1;
    _getDeviceList(currentPage);
  }
  _getMoreList() {
    currentPage += 1;
    _getDeviceList(currentPage);
  }

  // 获取设备列表
  _getDeviceList(int page) async {
    var params = {"page": "$page", "limit": "20"};
    if(searchTextController.text.isNotEmpty){
      params.addAll({"queryFuzzy": searchTextController.text});
    }

    ResultData data = await AppApi.getInstance().getProductList(params);
    if(data.code == 0){
      final list = data.data as List;
      if(list.isEmpty) return;

      final modelList = list.map((e) => ProductModel.fromJson(e)).toList();
      if(currentPage == 1) {
        _productList = modelList;
      }else{
        _productList.addAll(modelList);
      }

      setState(() {});

      return;
      _productList.forEach((element) async {
        final params = {"productId": "${element.id}"};
        final index = _productList.indexOf(element);
        ResultData data = await AppApi.getInstance().getProductInfo(params);
        if(data.code == 0){
          _productList[index] = ProductModel.fromJson(data.data);
          if(index == _productList.length - 1){
            setState((){});
          }
        }
      });

    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 加入收藏
  _addCollect(String productId) async {
    final params = {"productId": productId};
    ResultData data = await AppApi.getInstance().addCollectInfo(params);
    if(data.code == 0){
      SmartDialog.showToast("Success");
    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 批量控制


}
